package GUI;

import CDB.Categorias;
import CDB.Detalleproducto;
import CDB.Empleados;
import CDB.Permisos;
import CDB.Stock;
import CDB.Subcategoria;
import CDB.TableModelSD;
import CDB.Ventas;
import Negocios.ControlCategories;
import Negocios.ControlEmployee;
import Negocios.ControlPermissions;
import Negocios.ControlProduct;
import Negocios.ControlProductDetail;
import Negocios.ControlProviders;
import Negocios.ControlSales;
import Negocios.ControlSalesDetail;
import Negocios.ControlStock;
import Negocios.ControlSubcategory;
import java.beans.PropertyVetoException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;

/**
 *
 * @author ISC Erick y lightemp
 */
public class Catalogo extends javax.swing.JInternalFrame {

    private String nombreTabla = "";

    public Catalogo(String nombreTabla, String mensajeCatalogo) {
        initComponents();
        //Nombre del catalogo que se va a cargar
        this.nombreTabla = nombreTabla;
        //Recibo el titulo de la ventana
        lblDescripcion.setText(mensajeCatalogo);
        cargaTabla();

    }

    private void cargaTabla() {
        //--------------Refrescando la tabla----------------------
        tblCatalogo.setVisible(false);
        //Guardo los registros obtenidos en un lista
        List listRegistros = null;
        if (!nombreTabla.equals("")) {
            listRegistros = (obtenRegistros(nombreTabla));
        }
        //Compruebo que la lista alla traido registros
        if (listRegistros.size() > 0) {
            tblCatalogo.removeAll();
            //Creo el modelo para cargarlo en el Grid
            TableModelSD tableModel = new TableModelSD(nombreTabla, listRegistros);
            //Cargo el Grid
            tblCatalogo.setModel(tableModel);
            tblCatalogo.setVisible(true);// TODO add your handling code here:
        } else {
            JOptionPane.showMessageDialog(this, "No existen registros en "
                    + nombreTabla, "No hay registro en la DB", 2);
            tblCatalogo.removeAll();
            tblCatalogo.setVisible(false);// TODO add your handling code here:
            this.verifyContent();
        }
        if (this.nombreTabla.equals("Permisos")) {
            btnAgregar.setEnabled(false);
            btnEliminar.setEnabled(false);
        }
    }

    //Recibe el  nombre de la tabla que va a cargar
    //Retorna los registro en forma de lista
    private List obtenRegistros(String nombreTabla) {
        List listEntity = null;

        switch (nombreTabla) {
            case "Empleados":
                ControlEmployee employee = new ControlEmployee();
                listEntity = employee.selectAll();
                break;
            case "Productos":
                ControlProductDetail product = new ControlProductDetail();
                listEntity = product.selectAll();
                break;
            case "Proveedores":
                ControlProviders providers = new ControlProviders();
                listEntity = providers.selectAll();
                break;
            case "Stock":
                ControlStock stock = new ControlStock();
                listEntity = stock.selectAll();
                break;
            case "Categorias":
                ControlCategories categoria = new ControlCategories();
                listEntity = categoria.selectAll();
                break;
            case "Subcategorias":
                ControlSubcategory cs = new ControlSubcategory();
                listEntity = cs.selectAll();
                break;
            case "Permisos":
                ControlPermissions cp = new ControlPermissions();
                listEntity = cp.selectAll();
                break;
            case "Ventas":
                ControlSales cv = new ControlSales();
                listEntity = cv.selectAll();
                btnAgregar.setVisible(false);
                btnEditar.setVisible(false);
                btnBuscar.setVisible(false);
                btnEliminar.setText("Devolucion");
                break;
        }
        return listEntity;
    }

    private void verifyContent() {
        if (tblCatalogo.getRowCount() < 1) {
            btnBuscar.setEnabled(false);
            btnEditar.setEnabled(false);
            btnEliminar.setEnabled(false);
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        btnEditar = new javax.swing.JButton();
        btnAgregar = new javax.swing.JButton();
        btnEliminar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        btnCerrar = new javax.swing.JButton();
        btnBuscar = new javax.swing.JButton();
        btnActualizar = new javax.swing.JButton();
        lblDescripcion = new javax.swing.JLabel();
        jspTabla = new javax.swing.JScrollPane();
        tblCatalogo = new javax.swing.JTable();

        setBackground(new java.awt.Color(153, 153, 153));
        setTitle("Sales Tea Dispatcher - Catologo");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/IconosGenerales/Catalog.png"))); // NOI18N
        addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                formFocusGained(evt);
            }
        });

        jPanel1.setBackground(new java.awt.Color(153, 153, 153));

        btnEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IconosGenerales/Edit.png"))); // NOI18N
        btnEditar.setText("Editar");
        btnEditar.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        btnEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditarActionPerformed(evt);
            }
        });

        btnAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IconosGenerales/New.png"))); // NOI18N
        btnAgregar.setText("Agregar");
        btnAgregar.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        btnAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarActionPerformed(evt);
            }
        });

        btnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IconosGenerales/delete.png"))); // NOI18N
        btnEliminar.setText("Eliminar");
        btnEliminar.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IconosGenerales/Catalog.png"))); // NOI18N

        btnCerrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IconosGenerales/Cancel.png"))); // NOI18N
        btnCerrar.setText("Cerrar");
        btnCerrar.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        btnCerrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCerrarActionPerformed(evt);
            }
        });

        btnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IconosGenerales/Search.png"))); // NOI18N
        btnBuscar.setText("Buscar");
        btnBuscar.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });

        btnActualizar.setFont(new java.awt.Font("Dialog", 1, 11)); // NOI18N
        btnActualizar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IconosGenerales/Update.png"))); // NOI18N
        btnActualizar.setText("Actualizar");
        btnActualizar.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        btnActualizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnActualizarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(btnEditar, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE)
                            .addComponent(btnEliminar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnBuscar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnCerrar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnActualizar)
                            .addComponent(btnAgregar))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnActualizar, btnAgregar, btnBuscar, btnCerrar, btnEditar, btnEliminar, jLabel1});

        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnAgregar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnEditar, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnEliminar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnBuscar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnActualizar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnCerrar)
                .addGap(18, 27, Short.MAX_VALUE)
                .addComponent(jLabel1))
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnActualizar, btnAgregar, btnBuscar, btnCerrar, btnEditar, btnEliminar});

        lblDescripcion.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
        lblDescripcion.setText("En la tabla inferior se muestran los resultados.");

        jspTabla.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        jspTabla.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

        tblCatalogo.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        tblCatalogo.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        tblCatalogo.setAutoscrolls(false);
        tblCatalogo.setSelectionBackground(new java.awt.Color(255, 102, 0));
        jspTabla.setViewportView(tblCatalogo);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jspTabla, javax.swing.GroupLayout.DEFAULT_SIZE, 545, Short.MAX_VALUE)
                    .addComponent(lblDescripcion, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblDescripcion, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jspTabla, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCerrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCerrarActionPerformed
        try {
            this.setClosed(true);
            System.gc();
        } catch (PropertyVetoException ex) {
            this.dispose();
            System.gc();
        }
    }//GEN-LAST:event_btnCerrarActionPerformed

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        // TODO add your handling code here:
        switch (nombreTabla) {
            case "Empleados":
                ControlEmployee conEmp = new ControlEmployee();
                conEmp.deleteByEmpleado(
                        conEmp.selectOne(
                                (int) tblCatalogo.
                                getValueAt(
                                        tblCatalogo.getSelectedRow(), 0
                                )
                        )
                );
                break;
            case "Productos":

                try {
                    if (tblCatalogo.getSelectedRow() != -1) {
                        String Mensaje = "Esta ventana permite eliminar un producto \n o su detalle";
                        int idDetalle = (int) tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 0);
                        ControlProductDetail cpd = new ControlProductDetail();
                        Detalleproducto detalle = cpd.selectOne(idDetalle);
                        if (cpd.selectAll().size() > 1) {
                            EliminarProducto ep = new EliminarProducto(detalle, Mensaje);
                            if (exist(ep) == false) {
                                Principal.desktop.add(ep);
                                ep.setVisible(true);
                                ep.setLocation((Principal.desktop.getWidth() - ep.getWidth()) / 2,
                                        (Principal.desktop.getHeight() - ep.getHeight()) / 2);
                            } else {
                                ep.dispose();
                            }
                        } else {
                            int respuesta = JOptionPane.showConfirmDialog(this, "Al realizar la consulta del producto: "
                                    + detalle.getProducto().getNombre()
                                    + ", se encontró un solo tipo: "
                                    + detalle.getSubcategoria().getNombre()
                                    + "\n" + "¿Desea eliminar este producto?", "Confirmar eliminación", 0, 3);
                            if (respuesta == 0) {
                                try {
                                    ControlProduct cp = new ControlProduct();
                                    cp.delete(detalle.getProducto());
                                    JOptionPane.showMessageDialog(this, "Venta cancelada correctamente", "Cancelado", 1);
                                } catch (Exception e) {
                                    JOptionPane.showMessageDialog(this, "Ha ocurrido un error: " + e, "Error", 0);
                                    System.gc();
                                }
                            }
                        }
                    } else {
                        JOptionPane.showMessageDialog(this, "Seleccione un detalle de producto para poder editarlo",
                                "No ha seleccionado un detalle de producto", 2);
                    }
                } catch (Exception e) {
                }
                break;
            case "Proveedores":
                int idProveedor = (int) tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 0);//EliminarProveedor elimProv = new EliminarProveedor();
                ControlProviders cpro = new ControlProviders();
                cpro.delete(idProveedor);
                break;
            case "Stock":
                try {
                    ControlStock cs = new ControlStock();
                    Stock stock = new Stock();
                    stock.setIdstock((int) tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 0));
                    stock.setNombre(tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 1).toString());
                    stock.setCantidad((int) tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 2));
                    stock.setMinimo((short) tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 3));
                    stock.setPreciogranel((float) tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 4));
                    stock.setProveedores(
                            new ControlProviders().selectByName(
                                    tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 5).toString()
                            )
                    );
                    cs.deleteByObject(stock);
                } catch (Exception ex) {
                    Logger.getLogger(Catalogo.class.getName()).log(Level.SEVERE, null, ex);
                }
                break;
            case "Categorias":
                ControlCategories conCat = new ControlCategories();
                Categorias categoria = conCat.selectOne(
                        (int) tblCatalogo.
                        getValueAt(tblCatalogo.getSelectedRow(), 0)
                );
                conCat.deleteByCategoria(categoria);
                break;
            case "Subcategorias":
                ControlSubcategory conSub = new ControlSubcategory();
                Subcategoria subcategoria = conSub.selectOne(
                        (int) tblCatalogo.
                        getValueAt(tblCatalogo.getSelectedRow(), 0)
                );
                conSub.deleteBySubcategoria(subcategoria);
                break;
            case "Ventas":
                try {
                    //Revisa que la tabla tenga registros
                    if (tblCatalogo.getSelectedRow() > -1) {
                        int row = tblCatalogo.getSelectedRow();
                        int idVenta = (int) tblCatalogo.getValueAt(
                                row, 0);
                        //Obtengo una lista con los detalles de la venta elegida
                        List listdetalle = new ControlSalesDetail()
                                .selectByIdVenta(
                                        new ControlSales().selectOne(idVenta)
                                        .getIdventa()
                                );
                        //Comprueba la existencia de detalles de venta
                        if (listdetalle.size() > 0) {
                            //Crea la instancia de la ventana de Devoluciones
                            // y le paso el objeto venta
                            Devoluciones devolucion
                                    = new Devoluciones(
                                            new ControlSales().selectOne(idVenta),
                                            tblCatalogo.getValueAt(row, 1).toString(),
                                            tblCatalogo.getValueAt(row, 0).toString()
                                    );
                            //revisa si ya existe la ventana
                            if (exist(devolucion) == false) {
                                Principal.desktop.add(devolucion);
                                devolucion.setVisible(true);
                                devolucion.setLocation(
                                        (Principal.desktop.getWidth()
                                        - devolucion.getWidth()) / 2,
                                        (Principal.desktop.getHeight()
                                        - devolucion.getHeight()) / 2);
                            } else {
                                devolucion.dispose();
                            }
                        } else {
                            try {
                                //Si la venta no tiene detalles la borra
                                new ControlSales().delete(
                                        new ControlSales().selectOne(idVenta)
                                );
                                JOptionPane.showMessageDialog(this,
                                        "Venta cancelada correctamente",
                                        "Cancelado", 1);
                            } catch (Exception e) {
                                JOptionPane.showMessageDialog(this,
                                        "Ha ocurrido un error: " + e, "Error", 0);
                                System.gc();
                            }

                        }
                    } else {
                        JOptionPane.showMessageDialog(this, "Seleccione un detalle de producto para poder editarlo",
                                "No ha seleccionado un detalle de producto", 2);
                    }
                } catch (Exception e) {
                }

                break;
        }
        cargaTabla();
    }//GEN-LAST:event_btnEliminarActionPerformed

    public boolean exist(JInternalFrame frame) throws Exception {

        try {
            JInternalFrame iframes[] = Principal.desktop.getAllFrames();
            for (int i = 0; i < iframes.length; i++) {
                if (iframes[i].getTitle().equals(frame.getTitle())) {
                    iframes[i].moveToFront();
                    iframes[i].setSelected(true);
                    iframes[i].setLocation((Principal.desktop.getWidth() - iframes[i].getWidth()) / 2,
                            (Principal.desktop.getHeight() - iframes[i].getHeight()) / 2);
                    return true;
                }
            }
        } catch (Exception e) {
            throw e;
        }
        return false;
    }

    private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarActionPerformed
        try {
            switch (nombreTabla) {
                case "Empleados":
                    AltaEmpleado ae = new AltaEmpleado();
                    if (exist(ae) == false) {
                        Principal.desktop.add(ae);
                        ae.setVisible(true);
                        ae.setLocation((Principal.desktop.getWidth() - ae.getWidth()) / 2,
                                (Principal.desktop.getHeight() - ae.getHeight()) / 2);
                    } else {
                        ae.dispose();
                    }
                    break;
                case "Productos":
                    AltaProducto ap = new AltaProducto();
                    if (exist(ap) == false) {
                        Principal.desktop.add(ap);
                        ap.setVisible(true);
                        ap.setLocation((Principal.desktop.getWidth() - ap.getWidth()) / 2,
                                (Principal.desktop.getHeight() - ap.getHeight()) / 2);
                    } else {
                        ap.dispose();
                    }
                    break;
                case "Proveedores":
                    AltaProveedor apro = new AltaProveedor();
                    if (exist(apro) == false) {
                        Principal.desktop.add(apro);
                        apro.setVisible(true);
                        apro.setLocation((Principal.desktop.getWidth() - apro.getWidth()) / 2,
                                (Principal.desktop.getHeight() - apro.getHeight()) / 2);
                    } else {
                        apro.dispose();
                    }
                    break;
                case "Stock":
                    AltaStock ast = new AltaStock();
                    if (exist(ast) == false) {
                        Principal.desktop.add(ast);
                        ast.setVisible(true);
                        ast.setLocation((Principal.desktop.getWidth() - ast.getWidth()) / 2,
                                (Principal.desktop.getHeight() - ast.getHeight()) / 2);
                    } else {
                        ast.dispose();
                    }
                    break;
                case "Categorias":
                    AgregarCategoria ac = new AgregarCategoria();
                    if (exist(ac) == false) {
                        Principal.desktop.add(ac);
                        ac.setVisible(true);
                        ac.setLocation((Principal.desktop.getWidth() - ac.getWidth()) / 2,
                                (Principal.desktop.getHeight() - ac.getHeight()) / 2);
                    } else {
                        ac.dispose();
                    }
                    break;
                case "Subcategorias":
                    AgregarSubcategoria asub = new AgregarSubcategoria();
                    if (exist(asub) == false) {
                        Principal.desktop.add(asub);
                        asub.setVisible(true);
                        asub.setLocation((Principal.desktop.getWidth() - asub.getWidth()) / 2,
                                (Principal.desktop.getHeight() - asub.getHeight()) / 2);
                    } else {
                        asub.dispose();
                    }
                    break;
                case "Permisos":
                    break;
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "El error es: " + e,
                    "Ha ocurrido un error", 0);
        }
        cargaTabla();
    }//GEN-LAST:event_btnAgregarActionPerformed

    private void btnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarActionPerformed
        try {
            switch (nombreTabla) {
                case "Empleados":
                    if (tblCatalogo.getSelectedRow() > -1) {
                        ControlEmployee cem = new ControlEmployee();
                        Empleados emp = cem.selectOne(Integer.parseInt(tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 0).toString()));
                        try {
                            AltaEmpleado ae = new AltaEmpleado(emp);
                            if (exist(ae) == false) {
                                Principal.desktop.add(ae);
                                ae.setVisible(true);
                                ae.setLocation((Principal.desktop.getWidth() - ae.getWidth()) / 2, (Principal.desktop.getHeight() - ae.getHeight()) / 2);
                            } else {
                                ae.dispose();
                            }
                        } catch (Exception e) {
                            JOptionPane.showMessageDialog(this, "Ha ocurrido un error: " + e, "Error", 0);
                        }
                    } else {
                        JOptionPane.showMessageDialog(this, "Seleccione una opcion de la tabla para poder editarla.",
                                "Sin seleccion", 0);
                    }
                    break;
                case "Productos":
                    try {
                        if (tblCatalogo.getSelectedRow() != -1) {
                            int idDetalle = (int) tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 0);
                            ControlProductDetail cpd = new ControlProductDetail();
                            Detalleproducto detalle = cpd.selectOne(idDetalle);
                            AltaProducto ep = new AltaProducto(detalle);
                            if (exist(ep) == false) {
                                Principal.desktop.add(ep);
                                ep.setVisible(true);
                                ep.setLocation((Principal.desktop.getWidth() - ep.getWidth()) / 2,
                                        (Principal.desktop.getHeight() - ep.getHeight()) / 2);
                            } else {
                                ep.dispose();
                            }

                        } else {
                            JOptionPane.showMessageDialog(this, "Seleccione un detalle de producto para poder editarlo",
                                    "No ha seleccionado un detalle de producto", 2);
                        }
                    } catch (Exception e) {
                    }

                    break;
                case "Proveedores":
                    AltaProveedor apro = new AltaProveedor();
                    if (exist(apro) == false) {
                        Principal.desktop.add(apro);
                        apro.setVisible(true);
                        apro.setLocation((Principal.desktop.getWidth() - apro.getWidth()) / 2,
                                (Principal.desktop.getHeight() - apro.getHeight()) / 2);
                    } else {
                        apro.dispose();
                    }
                    break;
                case "Stock":
                    if (tblCatalogo.getSelectedRow() != -1) {
                        int id = (int) tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 0);
                        AumentarStock ast = new AumentarStock(id);
                        if (exist(ast) == false) {
                            Principal.desktop.add(ast);
                            ast.setVisible(true);
                            ast.setLocation((Principal.desktop.getWidth() - ast.getWidth()) / 2,
                                    (Principal.desktop.getHeight() - ast.getHeight()) / 2);
                        } else {
                            ast.dispose();
                        }
                    } else {
                        JOptionPane.showMessageDialog(this, "Seleccione un elemento de Stock para poder editarlo",
                                "No ha seleccionado un elemento de Stock", 2);
                    }
                    break;
                case "Categorias":
                    int idCategoria = (int) tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 0);
                    ControlCategories conCat = new ControlCategories();
                    Categorias categoria = conCat.selectOne(idCategoria);
                    AgregarCategoria ac = new AgregarCategoria(categoria, "Editar");
                    if (exist(ac) == false) {
                        Principal.desktop.add(ac);
                        ac.setVisible(true);
                        ac.setLocation((Principal.desktop.getWidth() - ac.getWidth()) / 2,
                                (Principal.desktop.getHeight() - ac.getHeight()) / 2);
                    } else {
                        ac.dispose();
                    }
                    break;
                case "Subcategorias":
                    AgregarSubcategoria asub = new AgregarSubcategoria();
                    if (exist(asub) == false) {
                        Principal.desktop.add(asub);
                        asub.setVisible(true);
                        asub.setLocation((Principal.desktop.getWidth() - asub.getWidth()) / 2,
                                (Principal.desktop.getHeight() - asub.getHeight()) / 2);
                    } else {
                        asub.dispose();
                    }
                    break;
                case "Permisos":
                    if (tblCatalogo.getSelectedRow() > -1) {
                        Permisos per = construirPermisos();
                        try {
                            AltaEmpleado ae = new AltaEmpleado(per);
                            if (exist(ae) == false) {
                                Principal.desktop.add(ae);
                                ae.setVisible(true);
                                ae.setLocation((Principal.desktop.getWidth() - ae.getWidth()) / 2, (Principal.desktop.getHeight() - ae.getHeight()) / 2);
                            } else {
                                ae.dispose();
                            }
                        } catch (Exception e) {
                            JOptionPane.showMessageDialog(this, "Ha ocurrido un error: " + e, "Error", 0);
                        }
                    } else {
                        JOptionPane.showMessageDialog(this, "Seleccione una opcion de la tabla para poder editarla.",
                                "Sin seleccion", 0);
                    }
                    break;
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "El error es: " + e,
                    "Ha ocurrido un error", 0);
        }
        cargaTabla();
    }//GEN-LAST:event_btnEditarActionPerformed
    private boolean obtenerValor(String val) {
        if (val.equals("Si")) {
            return true;
        } else {
            return false;
        }
    }

    private Permisos construirPermisos() {
        ControlEmployee ce = new ControlEmployee();
        Empleados em = ce.selectOneByName(tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 1).toString());
        Permisos per = new Permisos();
        per.setIdpermisos(Integer.parseInt(tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 0).toString()));
        per.setEmpleados(em);
        per.setPuntoventa(obtenerValor(tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 2).toString()));
        per.setRepaldodb(obtenerValor(tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 3).toString()));
        per.setRestaurardb(obtenerValor(tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 4).toString()));
        per.setAltaproducto(obtenerValor(tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 5).toString()));
        per.setElimeditproducto(obtenerValor(tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 6).toString()));
        per.setAltaproveedor(obtenerValor(tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 7).toString()));
        per.setElimeditproveedor(obtenerValor(tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 8).toString()));
        per.setAltaempleado(obtenerValor(tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 9).toString()));
        per.setElimeditempleado(obtenerValor(tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 10).toString()));
        per.setReporteventas(obtenerValor(tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 11).toString()));
        per.setReporteinventario(obtenerValor(tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 12).toString()));
        per.setCatalogoproductos(obtenerValor(tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 13).toString()));
        per.setCatalogoempleados(obtenerValor(tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 14).toString()));
        per.setCatalogoproveedor(obtenerValor(tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 15).toString()));
        per.setCatalogostock(obtenerValor(tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 16).toString()));
        per.setCatalogocategorias(obtenerValor(tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 17).toString()));
        per.setCatalogosubcategorias(obtenerValor(tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 18).toString()));
        per.setCatalogopermisos(obtenerValor(tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 19).toString()));
        per.setReporteproductos(obtenerValor(tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 20).toString()));
        per.setReporteempleados(obtenerValor(tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 21).toString()));
        per.setAltacategoria(obtenerValor(tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 22).toString()));
        per.setElimcategoria(obtenerValor(tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 23).toString()));
        per.setAltasubcategoria(obtenerValor(tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 24).toString()));
        per.setElimsubcategoria(obtenerValor(tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 25).toString()));
        per.setCortedecaja(obtenerValor(tblCatalogo.getValueAt(tblCatalogo.getSelectedRow(), 26).toString()));

        return per;
    }
    private void formFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_formFocusGained
    }//GEN-LAST:event_formFocusGained

    private void btnActualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnActualizarActionPerformed
        cargaTabla();
    }//GEN-LAST:event_btnActualizarActionPerformed

    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
        //se presiono el boton
        String msg = JOptionPane.showInputDialog("ingrese el nombre que desa buscar");
        int filas = tblCatalogo.getRowCount();
        int columnas = tblCatalogo.getColumnCount();
        String val = msg;

        for (int fila = 0; fila < filas; fila++) {
            for (int columna = 0; columna < columnas; columna++) {
                String word = String.valueOf(tblCatalogo.getValueAt(fila,
                        columna));
                if (val == null ? word == null : val.toLowerCase().equals(word.toLowerCase())) {
                    tblCatalogo.changeSelection(fila, columna, false, false);
                    JOptionPane.showMessageDialog(btnBuscar, "Ha sido localizado la información: " + msg + "\nfila: "
                            + (fila + 1) + "\ncolumna: "
                            + (columna + 1));
                    columna = columnas;
                    fila = filas;
                }
            }
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_btnBuscarActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnActualizar;
    private javax.swing.JButton btnAgregar;
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnCerrar;
    private javax.swing.JButton btnEditar;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jspTabla;
    private javax.swing.JLabel lblDescripcion;
    private javax.swing.JTable tblCatalogo;
    // End of variables declaration//GEN-END:variables
}
